package tool

import java.io.File
import java.net.{URLDecoder, URLEncoder}
import java.nio.file.Files

import utils.Implicits._
import ReportPojo._
import command.CommandUtils
import controllers.routes
import dao.{ModeDao, UserDao}
import javax.inject.Inject
import models.Tables.MissionRow
import org.apache.commons.io.FileUtils
import org.joda.time.DateTime
import org.zeroturnaround.zip.ZipUtil
import play.api.mvc.RequestHeader
import tool.Pojo.{CommandData, MyInputFile, ReportHomeData}
import utils.Utils

import scala.concurrent.ExecutionContext.Implicits.global
import shared.VarTool
import implicits.Implicits._

/**
 * Created by Administrator on 2019/10/11
 */

object ReportTool {

  def produceZip(mission: MissionRow)(implicit userDao: UserDao, tool: Tool, modeDao: ModeDao): Unit = {
    val missionIdDir = Tool.getMissionIdDir(mission)
    val resultDir = new File(missionIdDir, "result")
    val resultFile = new File(missionIdDir, s"result.zip")
    val htmlFile = ReportTool.produceHtml(mission)
    val pdfFile = ReportTool.producePdf(mission)
    val commentFile = ReportTool.produceComment(mission)
    val treeFile = ReportTool.produceTreeHtmlFile(mission)
    ZipUtil.pack(resultDir, resultFile)
  }

  def produceHtml(mission: MissionRow)(implicit userDao: UserDao) = {
    val path = s"${Tool.reportDirName}/src/"
    val missionIdDir = Tool.getMissionIdDir(mission)
    val reportDir = Tool.getReportDir(missionIdDir)
    val resultDir = Tool.getUserResultDir(mission)
    val srcDir = new File(Utils.dataDir, "src")
    FileUtils.copyDirectoryToDirectory(srcDir, reportDir)
    implicit val reportData = ReportTool.getReportData(missionIdDir)
    val resultPath = s"${Tool.reportDirName}/sources/"
    val userId = mission.userId
    val htmlFile = new File(resultDir, "report.html")
    val htmlEnFile = new File(resultDir, "report_en.html")
    val unitFile = new File(missionIdDir, "unit.txt")
    val f = userDao.selectById(userId).map { user =>
      val unit = user.unit
      val reportInfo = ReportTool.getReportInfo(unit)
      val htmlStr = views.html.user.report.html.right(path, reportInfo, resultPath).toString()
      htmlStr.toFile(htmlFile)
      val htmlEnStr = views.html.user.reportEn.html.right(path, reportInfo, resultPath).toString()
      htmlEnStr.toFile(htmlEnFile)
      user.unit.toFile(unitFile)
    }
    Utils.execFuture(f)
    htmlFile
  }

  def produceTreeHtmlFile(mission: MissionRow)(implicit userDao: UserDao, tool: Tool, modeDao: ModeDao) = {
    val resultDir = Tool.getUserResultDir(mission)
    val htmlFile = new File(resultDir, "tree.html")
    val dir = new File(resultDir, "data_result")
    val workspaceDir = new File(resultDir, "produce_tree")
    val command =
      s"""
         |tree -H data_result  -o ${htmlFile.unixPath} ${dir.unixPath}
         |""".stripMargin
    val execComand = CommandUtils.orderCallLinuxScript(workspaceDir, List(command))
    if (!Tool.isTestMode) {
      workspaceDir.deleteQuietly
    }
    htmlFile
  }

  def produceCoverHtml(mission: MissionRow)(implicit userDao: UserDao) = {
    val path = s"${Tool.reportDirName}/src/"
    val missionIdDir = Tool.getMissionIdDir(mission)
    val reportDir = Tool.getReportDir(missionIdDir)
    val resultDir = Tool.getUserResultDir(mission)
    val userId = mission.userId
    val htmlFile = new File(resultDir, "cover.html")
    val f = userDao.selectById(userId).map { user =>
      val unit = user.unit
      val reportInfo = ReportTool.getReportInfo(unit)
      val htmlStr = views.html.user.report.pdf.cover(path, reportInfo).toString()
      htmlStr.toFile(htmlFile)
    }
    Utils.execFuture(f)
    htmlFile
  }

  def produceReportHtml(mission: MissionRow)(implicit userDao: UserDao) = {
    val path = s"${Tool.reportDirName}/src/"
    val missionIdDir = Tool.getMissionIdDir(mission)
    val reportDir = Tool.getReportDir(missionIdDir)
    val resultDir = Tool.getUserResultDir(mission)
    val srcDir = new File(Utils.dataDir, "src")
    FileUtils.copyDirectoryToDirectory(srcDir, reportDir)
    implicit val reportData = ReportTool.getReportData(missionIdDir)
    val resultPath = s"${Tool.reportDirName}/sources/"
    val userId = mission.userId
    val htmlFile = new File(resultDir, "pdf_report.html")
    val htmlEnFile = new File(resultDir, "pdf_report_en.html")
    val unitFile = new File(missionIdDir, "unit.txt")
    val f = userDao.selectById(userId).map { user =>
      val unit = user.unit
      val reportInfo = ReportTool.getReportInfo(unit)
      val htmlStr = views.html.user.report.pdf.report(path, reportInfo, resultPath).toString()
      htmlStr.toFile(htmlFile)
      val htmlEnStr = views.html.user.reportEn.pdf.report(path, reportInfo, resultPath).toString()
      htmlStr.toFile(htmlFile)
      htmlEnStr.toFile(htmlEnFile)
      user.unit.toFile(unitFile)
    }
    Utils.execFuture(f)
    (htmlFile, htmlEnFile)
  }

  def producePdf(mission: MissionRow)(implicit userDao: UserDao, tool: Tool, modeDao: ModeDao) = {
    val resultDir = Tool.getUserResultDir(mission)
    val (htmlFile, htmlEnFile) = ReportTool.produceReportHtml(mission)
    val coverHtmlFile = ReportTool.produceCoverHtml(mission)
    val pdfFile = new File(resultDir, "report.pdf")
    val pdfEnFile = new File(resultDir, "report_en.pdf")
    val tmpDir = Tool.createTempDirectory("tmpDir")
    val userId = mission.userId
    val unitF = userDao.selectById(userId).map { user =>
      user.unit
    }
    val f = unitF.map { unit =>
      unit == "深圳市绘云生物科技有限公司"
    }
    val isHuiyun = Utils.execFuture(f)
    val isXXX = Utils.execFuture(unitF.map(_ == "XXX公司"))
    val coverPdfFile = new File(resultDir, "cover.pdf")
    if (isHuiyun) {
      new File(Utils.pdfDir, "huiyun_home.pdf").copyTo(coverPdfFile)
    }
    val contentPdfFile = new File(resultDir, "content.pdf")
    val contentPdfEnFile = new File(resultDir, "conten_en.pdf")
    val command =
      if (isHuiyun) {
        s"""
           |#wkhtmltopdf --dump-default-toc-xsl >default.xsl
           |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0.5in --margin-bottom 0.5in --margin-left 0.5in  --margin-right 0.5in --footer-center [page] toc --xsl-style-sheet ${Utils.tocFile.unixPath} ${htmlFile.unixPath} ${contentPdfFile.unixPath}
           |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0.5in --margin-bottom 0.5in --margin-left 0.5in  --margin-right 0.5in --footer-center [page] toc --xsl-style-sheet ${Utils.tocFile.unixPath} ${htmlEnFile.unixPath} ${contentPdfEnFile.unixPath}
           |pdfunite  ${coverPdfFile.unixPath} ${contentPdfFile.unixPath}  ${pdfFile.unixPath}
           |pdfunite  ${coverPdfFile.unixPath} ${contentPdfEnFile.unixPath}  ${pdfEnFile.unixPath}
           |""".stripMargin
      } else {
        if (isXXX) {
          s"""
             |#wkhtmltopdf --dump-default-toc-xsl >default.xsl
             |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0in --margin-bottom 0in --margin-left 0in  --margin-right 0in   ${coverHtmlFile.unixPath} ${coverPdfFile.unixPath}
             |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0.5in --margin-bottom 0.5in --margin-left 0.5in  --margin-right 0.5in --footer-center [page] toc --xsl-style-sheet ${Utils.tocFile.unixPath} ${htmlFile.unixPath} ${contentPdfFile.unixPath}
             |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0.5in --margin-bottom 0.5in --margin-left 0.5in  --margin-right 0.5in --footer-center [page] toc --xsl-style-sheet ${Utils.tocEnFile.unixPath} ${htmlEnFile.unixPath} ${contentPdfEnFile.unixPath}
             |pdfunite  ${contentPdfFile.unixPath}  ${pdfFile.unixPath}
             |pdfunite   ${contentPdfEnFile.unixPath}  ${pdfEnFile.unixPath}
             |""".stripMargin
        } else {
          s"""
             |#wkhtmltopdf --dump-default-toc-xsl >default.xsl
             |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0in --margin-bottom 0in --margin-left 0in  --margin-right 0in   ${coverHtmlFile.unixPath} ${coverPdfFile.unixPath}
             |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0.5in --margin-bottom 0.5in --margin-left 0.5in  --margin-right 0.5in --footer-center [page] toc --xsl-style-sheet ${Utils.tocFile.unixPath} ${htmlFile.unixPath} ${contentPdfFile.unixPath}
             |${Utils.wkhtmltopdf} --orientation Portrait --page-size A4 --margin-top 0.5in --margin-bottom 0.5in --margin-left 0.5in  --margin-right 0.5in --footer-center [page] toc --xsl-style-sheet ${Utils.tocEnFile.unixPath} ${htmlEnFile.unixPath} ${contentPdfEnFile.unixPath}
             |pdfunite  ${coverPdfFile.unixPath} ${contentPdfFile.unixPath}  ${pdfFile.unixPath}
             |pdfunite  ${coverPdfFile.unixPath} ${contentPdfEnFile.unixPath}  ${pdfEnFile.unixPath}
             |""".stripMargin
        }
      }
    val execComand = Utils.orderCallLinuxScript(tmpDir, List(command))
    Tool.deleteDirectory(tmpDir)
    if (!Tool.isTestMode) {
      List(coverHtmlFile, htmlFile, htmlEnFile, coverPdfFile, contentPdfFile, contentPdfEnFile).foreach { file =>
        file.deleteQuietly
      }
    }

    pdfFile
  }

  def produceComment(mission: MissionRow)(implicit userDao: UserDao, tool: Tool) = {
    val workspaceDir = Tool.getMissionWorkspaceDirById(mission)
    val resultDir = Tool.getUserResultDir(mission)
    val commentFile = new File(resultDir, "项目备注.txt")
    val configFile = new File(workspaceDir, "config.txt")
    val isInter = configFile.csvLines.filter(_ (0) == "isInter").map(_ (1)).head
    if (isInter == "auto") {
      val comments = workspaceDir.listFiles().toList.filter(_.getName.contains("_vs_")).flatMap { dir =>
        val inConfigFile = new File(dir, "00/config.csv")
        val commentFile = new File(dir, "00/comment.csv")
        val inCommentLines = if (commentFile.exists()) {
          commentFile.csvLines.drop(1).map(_ (1)).map { x =>
            s"在本项目下属“${dir.getName}”的比较分析中，${x}"
          }
        } else List[String]()

        val inIsInter = inConfigFile.csvLines.filter(_ (0) == "isInter").map(_ (1)).head
        val potentialCommentLine = inIsInter match {
          case "oplsda" => s"在本项目下属“${dir.getName}”的比较分析中，由于OPLS-DA分析未检出差异代谢物，所以将差异代谢物选取规则变更为多维单维结果取并集。"
          case "uni" => s"在本项目下属“${dir.getName}”的比较分析中，由于单维分析未检出差异代谢物，所以将差异代谢物选取规则变更为多维单维结果取并集。"
          case _ => ""
        }

        val isPaired = inConfigFile.csvLines.filter(_ (0) == "isPaired").map(_ (1)).head
        val pairLines = isPaired match {
          case "T" => val line = s"在本项目下属“${dir.getName}”的比较分析中，成功进行了配对检验。"
            List(line)
          case "F" => Nil
        }

        potentialCommentLine :: inCommentLines ::: pairLines
      }.notEmptyLines
      comments.toFile(commentFile)
    }
    commentFile
  }

  def getReportInfo(unit: String) = {
    val reportInfo = ReportInfo()
    unit match {
      case "XXX公司" => reportInfo.copy(isXxx = true, phone = "")
      case _ => reportInfo.copy(isMet = true, phone = "400-867-2686")
    }
  }

  def getTableData(file: File) = {
    val lines = file.csvLines.notEmptyLines
    TableData(lines.head, lines.drop(1))
  }

  def getTableData(file: File, topName: String) = {
    val lines = file.csvLines.notEmptyLines
    val beforeHeaders = lines.head
    val headers = (topName) :: (beforeHeaders.filter(_ != topName))
    val i = beforeHeaders.indexOf(topName)
    val newLines = lines.drop(1).map { columns =>
      columns(i) :: (columns.filter(_ != columns(i)))
    }
    TableData(headers, newLines)
  }

  def getTableDataWithColor(file: File) = {
    val showHeaders = List("Metabolite", "Class", "HMDB", "KEGG", "Uni_P", "Uni_FDR", "FC", "log2FC", "OPLSDA_VIP")
    val lines = file.csvLines.notEmptyLines
    val beforeHeaders = lines.head
    val showI = showHeaders.map { header =>
      beforeHeaders.indexOf(header)
    }.filter(x => x != -1)
    val headers = showI.map(beforeHeaders(_))
    val newLines = lines.drop(1).map { columns =>
      showI.map(columns(_))
    }
    val colorLines = newLines.map { columns =>
      columns.zipWithIndex.map { case (column, j) =>
        val header = headers(j)
        if (j >= 4 && column.isDouble) {
          val db = column.toDouble
          val fixedColumn = db.toFixed(4).toString
          val showColumn = if (header == "Uni_P" || header == "Uni_FDR") {
            if (db < 0.0001) "<0.0001" else fixedColumn
          } else fixedColumn
          val color = Tool.getColor(header, column)
          (showColumn, color)
        } else (column, "")
      }
    }
    ColorTableData(headers, colorLines)
  }

  def getReportData(missionIdDir: File) = {
    val sourcesDir = Tool.getSourceDir(missionIdDir)
    val preDir = new File(sourcesDir, "Preprocessed_Data")
    val treatmentDir = new File(sourcesDir, "Treatment")
    val sampleInfoFile = new File(preDir, "Class_Info.csv")
    val sampleInfoData = ReportTool.getTableData(sampleInfoFile)
    val superClassCountFile = new File(sourcesDir, "Quality_Control/Class_Count.csv")
    val superClassCount = if (superClassCountFile.exists()) {
      superClassCountFile.csvLines.lineMap.filter { map =>
        map("class") != "Unknown"
      }.map(_ ("count").toInt).sum
    } else 0
    val treats = treatmentDir.listFiles().filter(_.getName.contains("vs")).map(_.getName)
    val workspaceDir = new File(missionIdDir, "workspace")
    val configFile = new File(workspaceDir, "config.txt")
    val configMap = configFile.csvLines.map { columns =>
      (columns(0), columns(1))
    }.toMap

    val configDatas = treats.map { treat =>
      val treatDir = new File(workspaceDir, treat)
      val libTypesAbbr = configMap(VarTool.libTypes).split(";")
      val libTypes = libTypesAbbr.map { x =>
        VarTool.libTypeMap(x)
      }
      val groups = treat.split("_vs_")
      val isMul = groups.size > 2
      val pValue = if (isMul) configMap("diffMethod.kwP") else configMap("diffMethod.pValue")
      val fdr = if (isMul) configMap("diffMethod.kwFdr") else configMap("diffMethod.fdr")
      val isSelfCor = (configMap("cor.isSelfCorExec") == "T")
      val isCor = (configMap("cor.isCorExec") == "T")
      val isParCor = (configMap("cor.isParCorExec") == "T")
      val isEnrichExec = (configMap(VarTool.isEnrichExec) == "T")
      val isPathwayExec = (configMap(VarTool.isPathwayExec) == "T")
      val isIPathExec = (configMap(VarTool.isIPathExec) == "T")
      val isDiagnoseExec = (configMap("diagnoseIsExec") == "yes")
      ConfigData(pValue, fdr, configMap("diffMethod.log2FC"), configMap(VarTool.vipName), libTypes, libTypesAbbr, configMap("species"),
        configMap("cor.coe"), configMap("cor.p"), groups, configMap("rfTop"), configMap("svmTop"), isMul, isSelfCor, isCor, isParCor,
        isEnrichExec, isPathwayExec, isIPathExec, isDiagnoseExec)
    }

    val outerData = {
      val extraDataDir = new File(workspaceDir, "cor_extra_data")
      val names = extraDataDir.listFiles().map(_.namePrefix)
      val hasQc = (new File(sourcesDir, "Preprocessed_Data/Class_Info.csv")).csvLines.
        selectOneColumn("classnote").contains("QC")
      OuterData(names, hasQc)
    }

    val resultDatas = treats.map { treat =>
      val treatDir = new File(treatmentDir, treat)
      val uniDir = treatDir.listFiles().find(_.getName.contains("Univariate_Analysis")).get
      val diffFile = new File(uniDir, "AllMet_Z_Score.csv")
      val uniDiffCount = if (!diffFile.exists()) 0 else diffFile.csvLines.head.size - 1
      val corDir = treatDir.listFiles().find(_.getName.contains("Correlation_Analysis")).map(_.getName)
      val pathwayDir = treatDir.listFiles().find(_.getName.contains("Pathway_Analysis")).map(_.getName)
      val diagnoseDir = treatDir.listFiles().find(_.getName.contains("Diagnose")).map(_.getName)
      val potentialDir = treatDir.listFiles().find(_.getName.contains("Potential_Biomarkers")).get
      val markersFile = new File(potentialDir, "Markers.csv")
      val markersData = ReportTool.getTableDataWithColor(markersFile)
      val hasBubble = treatDir.listFiles().find(_.getName.contains("Pathway_Analysis")).map { dir =>
        val file = new File(dir, "Pathway_Analysis/Pathway_Bubbleplot.png")
        file.exists()
      }.getOrElse(false)
      val vennPlotFile = new File(potentialDir, "Venn_Plot.png")
      val hasVennPlot = vennPlotFile.exists()
      val keggIds = markersFile.csvLines.lineMap.map(_ ("kegg")).notNALines
      val hasEnrichMap = treatDir.listFiles().find(_.getName.contains("Pathway_Analysis")).map { dir =>
        val enrichDir = new File(dir, "Enrichment_Analysis")
        if (enrichDir.exists()) {
          enrichDir.listFiles().map { subDir =>
            val file = new File(subDir, "MSEA_Result.csv")
            (subDir.getName, file.exists())
          }.toMap
        } else Map[String, Boolean]()
      }.getOrElse(Map.empty)
      ResultData(uniDiffCount, corDir, pathwayDir, diagnoseDir, markersData, potentialDir.getName, uniDir.getName,
        hasBubble, keggIds, hasVennPlot, hasEnrichMap)
    }

    val reportHome = {
      val map = configMap
      val reportHomeMap = Tool.getReportHomeMap(configMap)
      Utils.to[ReportHomeData].from(reportHomeMap).get
    }
    val extraData = {
      val time = (new DateTime()).toString("yyyy-MM-dd")
      ExtraData(time)
    }
    val outConfigData = {
      val anaKind = configMap("anaKind")
      val withRatio = (anaKind != "allMet")

      OutConfigData(withRatio)

    }

    val summaryData = {
      val sigMetFile = new File(sourcesDir, "Treatment/Sig_Met_Summary/Sig_Met_Venn_Data.csv")
      val sigMetTable = ReportTool.getTableData(sigMetFile)
      val selfCorPngFile = new File(sourcesDir, "Treatment/Correlation_Summary/Intra_Correlation_Venn_Plot.png")
      val hasSelfCor = selfCorPngFile.exists()
      val csDir = new File(sourcesDir, "Treatment/Correlation_Summary")
      val uploads = if (csDir.exists()) {
        csDir.listFiles().toList.filter(_.isDirectory).map { dir =>
          val exist = new File(dir, "Inter_Correlation_Venn_Plot.png").exists()
          val parExist = new File(dir, "Inter_Partial_Correlation_Venn_Plot.png").exists()
          UploadData(dir.getName, exist, parExist)
        }
      } else {
        List[UploadData]()
      }
      val sigMetPngFile = new File(sourcesDir, "Treatment/Sig_Met_Summary/Sig_Met_Venn_Plot.png")
      val hasSigMet = sigMetPngFile.exists()
      SummaryData(hasSigMet, sigMetTable, hasSelfCor, uploads)
    }

    ReportData(sampleInfoData, superClassCount, treats, configDatas, resultDatas, outerData, reportHome, extraData,
      outConfigData, summaryData)
  }


  def dirPdf2png(dir: File) = {

    def loop(file: File): Unit = {
      for (file <- file.listFiles()) {
        if (file.isDirectory) {
          loop(file)
        }
        else {
          if (file.getName.endsWith(".pdf")) {
            val filePath = file.getAbsolutePath
            val targetFile = new File(file.getParent, s"${file.namePrefix}.png")
            Utils.pdf2png(file, targetFile)
          }

        }
      }
    }

    loop(dir)

  }

  def getPdf2PngFiles(pdfDir: File) = {
    def loop(acc: List[(File, File)], files: List[File]): List[(File, File)] = {
      files match {
        case Nil => acc
        case x :: xs if x.isFile && x.getName.endsWith(".pdf") =>
          val filePath = x.getAbsoluteFile
          val targetFile = new File(x.getParent, s"${
            x.namePrefix
          }.png")
          val t = (x, targetFile)
          loop(t :: acc, xs)
        case x :: xs if x.isDirectory =>
          loop(acc, xs ::: x.listFiles().toList)
        case x :: xs =>
          loop(acc, xs)
      }
    }

    loop(List(), List(pdfDir))
  }

  def pdf2pngsFast(workspaceDir: File, pdfDir: File)(implicit myInput: MyInputFile) = {
    val files = getPdf2PngFiles(pdfDir)
    val commmands = files.map {
      case (pdfFile, pngFile) =>
        s"""
           |convert  -density 300 "${
          pdfFile.unixPath
        }"[0] "${
          pngFile.unixPath
        }"
           |""".stripMargin
    }
    CommandData(workspaceDir, commmands)
  }

  def dirPdf2pngFast(dir: File)(implicit tool: Tool, modeDao: ModeDao) = {

    def loop(acc: List[(File, File)], files: List[File]): List[(File, File)] = {
      files match {
        case Nil => acc
        case x :: xs if x.isFile && x.getName.endsWith(".pdf") =>
          val filePath = x.getAbsoluteFile
          val targetFile = new File(x.getParent, s"${
            x.namePrefix
          }.png")
          val t = (x, targetFile)
          loop(t :: acc, xs)
        case x :: xs if x.isDirectory =>
          loop(acc, xs ::: x.listFiles().toList)
        case x :: xs =>
          loop(acc, xs)
      }
    }

    val files = loop(List(), List(dir))
    Utils.pdf2pngs(files)
  }


  def pdf2pngs(sourceDir: File, targetDir: File) = {

    def loop(file: File): Unit = {
      for (file <- file.listFiles()) {
        if (file.isDirectory) {
          loop(file)
        } else {
          if (file.getName.endsWith(".pdf")) {
            val filePath = file.getAbsolutePath
            val sourcePath = sourceDir.getAbsolutePath
            val targetFile = new File(targetDir, filePath.replace(sourcePath, ""))
            val targetPngFile = new File(targetFile.getParentFile, s"${
              file.namePrefix
            }.png")
            Utils.pdf2png(file, targetPngFile)
          }

        }
      }
    }

    loop(sourceDir)

  }

  def svg2pngs(sourceDir: File, targetDir: File) = {
    def loop(file: File): Unit = {
      for (file <- file.listFiles()) {
        if (file.isDirectory) {
          loop(file)
        } else {
          if (file.getName.endsWith(".svg")) {
            val filePath = file.getAbsolutePath
            val sourcePath = sourceDir.getAbsolutePath
            val targetFile = new File(targetDir, filePath.replace(sourcePath, ""))
            val targetPngFile = new File(targetFile.getParentFile, s"${
              file.namePrefix
            }.png")
            Utils.svg2png(file, targetFile)
          }
        }
      }
    }

    loop(sourceDir)
  }


  def dirSvg2png(dir: File) = {

    def loop(file: File): Unit = {
      for (file <- file.listFiles()) {
        if (file.isDirectory) {
          loop(file)
        } else {
          if (file.getName.endsWith(".svg")) {
            val filePath = file.getAbsolutePath
            val targetFile = new File(file.getParent, s"${
              file.namePrefix
            }.png")
            Utils.svg2png(file, targetFile)
          }
        }
      }
    }

    loop(dir)

  }

}
